<template>
	<el-card class="box-card" style="width: 600px; margin: 100px auto">
		<template #header>
			<div class="card-header">
				<span>欢迎光临【京西正版】</span>
			</div>
		</template>
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			status-icon
			:rules="rules"
			label-width="120px"
			class="demo-ruleForm"
		>
			<el-form-item label="用户名" prop="username" label-width="80px">
				<el-input v-model.trim="ruleForm.username" />
			</el-form-item>

			<el-form-item label="密码" prop="pass" label-width="80px">
				<el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
			</el-form-item>

			<el-form-item label="确认密码" prop="checkPass" label-width="80px">
				<el-input
					v-model="ruleForm.checkPass"
					type="password"
					autocomplete="off"
				/>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="submitForm(ruleFormRef)"
					>登录</el-button
				>
				<el-button @click="resetForm(ruleFormRef)">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script setup>
	import { ref, reactive } from "vue";
	import "./login.scss";

	import { useRouter, useRoute } from "vue-router";
	import { useStore } from 'vuex'
    const router = useRouter()
	const store = useStore()

	const ruleFormRef = ref();

	const reUsername = /^[a-z]\w{5,19}$/i;
	const checkUsername = (rule, value, callback) => {
		if (!value) {
			return callback(new Error("请输入用户名"));
		}
		setTimeout(() => {
			if (!reUsername.test(value)) {
				return callback(new Error("用户名必须是6~20位单词字符且必须以字母开头"));
			}
			return callback();
		}, 1000);
	};

	const validatePass = (rule, value, callback) => {
		if (value === "") {
			callback(new Error("请输入密码"));
		} else {
			if (ruleForm.checkPass !== "") {
				if (!ruleFormRef.value) return;
				ruleFormRef.value.validateField("checkPass", () => null);
			}
			callback();
		}
	};

	const validatePass2 = (rule, value, callback) => {
		if (value === "") {
			callback(new Error("Please input the password again"));
		} else if (value !== ruleForm.pass) {
			callback(new Error("Two inputs don't match!"));
		} else {
			callback();
		}
	};

	const ruleForm = reactive({
		pass: "",
		checkPass: "",
		username: "",
	});

	const rules = reactive({
		pass: [{ validator: validatePass, trigger: "blur" }],
		checkPass: [{ validator: validatePass2, trigger: "blur" }],
		username: [{ validator: checkUsername, trigger: "blur" }],
	});

	const submitForm = (formEl) => {
		if (!formEl) return;
		formEl.validate((valid) => {
			if (valid) {
				console.log("submit!");

				store.dispatch('user/setUsername', ruleForm.username)
				router.push({ path: '/' });
                
			} else {
				console.log("error submit!");
				return false;
			}
		});
	};

	const resetForm = (formEl) => {
		if (!formEl) return;
		formEl.resetFields();
	};
</script>